package com.kuns.subject.domian.service.impl;

import com.alibaba.fastjson.JSON;
import com.kuns.subject.common.entity.PageResult;
import com.kuns.subject.common.enums.IsDeletedFlagEnum;
import com.kuns.subject.domian.convert.SubjectInfoConverter;
import com.kuns.subject.domian.entity.SubjectInfoBO;
import com.kuns.subject.domian.entity.SubjectOptionBO;
import com.kuns.subject.domian.handler.subject.SubjectTypeHandler;
import com.kuns.subject.domian.handler.subject.SubjectTypeHandlerFactory;
import com.kuns.subject.domian.service.SubjectInfoDomainService;
import com.kuns.subject.infra.basic.entity.SubjectInfo;
import com.kuns.subject.infra.basic.entity.SubjectLabel;
import com.kuns.subject.infra.basic.entity.SubjectMapping;
import com.kuns.subject.infra.basic.service.SubjectInfoService;
import com.kuns.subject.infra.basic.service.SubjectLabelService;
import com.kuns.subject.infra.basic.service.SubjectMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.subjectInfoBO:{}", JSON.toJSONString(subjectInfoBO));
        }
        // 将bo转成infra层的entity,
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToEntity(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.code);
        // 插入题目基本信息
        subjectInfoService.insert(subjectInfo);
        subjectInfoBO.setId(subjectInfo.getId());

        // 插入题目类型
        // 使用工厂模式+策略模式来进行插入,避免大量的if来判断题目类型然后调用对应的插入服务
        // 例如如果subjectType == 1，调用单选题domain层的插入服务，产生大量if else，
        // 扩展性差，如果来多一个其它类型的又要改原有的代码加if else
        // 所以采用工厂模式，根据题目类型从工厂中拿到对应的策略handler类来完成对应类型的插入操作
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfoBO.getSubjectType());
        handler.add(subjectInfoBO);

        // 插入题目映射
        // 一个题目可以有多个分类，例如可以属于框架、并发
        // 一个题目也可以有多个标签。 例如 SpringBoot、SpringMVC
        // 所以插入题目映射的时候
        List<Long> labelIdList = subjectInfoBO.getLabelIds();
        List<Long> categoryIdList = subjectInfoBO.getCategoryIds();
        List<SubjectMapping> subjectMappingList = new ArrayList<>();
        categoryIdList.forEach(categoryId -> {
            labelIdList.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setSubjectId(subjectInfoBO.getId());
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.code);
                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);
    }

    @Override
    public PageResult<SubjectInfoBO> queryPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());

        // 查询数量
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToEntity(subjectInfoBO);
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId());
        if (count == 0) { // 数量为0直接返回分页对象就行了，不用继续后续的赋值了
            return pageResult;
        }

        // 查询当前页的题目列表
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo
                , subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        // 将entity转成bo
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConverter.INSTANCE.convertEntityListToBoList(subjectInfoList);
        pageResult.setRecords(subjectInfoBOList);
        pageResult.setTotal(count);

        return pageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        // 查询题目信息详情
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());

        // 根据题目类型查询具体题目内容信息，例如单选题就要查询出选项，简单题就要查询出答案
        // 使用工厂模式，根据题目类型来获取具体的策略类
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO subjectOptionBO = handler.queryOption(subjectInfoBO.getId());

        SubjectInfoBO boResult = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(subjectInfo, subjectOptionBO);

        // 查询标签名
        // 先根据题目id在题目关系表查询出所有的labelId
        // 再根据这个labelIdList查询出所有的label获取标签名
        List<String> labelNameList = new ArrayList<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfoBO.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.code);
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIdList);
        labelNameList = subjectLabelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        boResult.setLabelNameList(labelNameList);
        return boResult;
    }
}
